import json
from time import timezone
from django import http
from . import  utils
# Create your views here.
from django.db import transaction
from django.views import View
from pymysql import DatabaseError

from houses.models import House
from orders.models import Order
from users.models import User


# PUT /api/v1.0/orders/
from utils.response_code import RET


class OrderInfoView(View):
    def get(self, request):
        """订单界面"""
        role = request.GET.get('role')
        user = request.user
        # user_id = user.id

        if role is None:
            return http.JsonResponse({'code': RET.PARAMERR,
                                      'errmsg': '参数错误'})
        if role not in ['custom', 'landlord']:
            return http.JsonResponse({'code': RET.PARAMERR,
                                      'errmsg': '角色错误'})
        if role == 'custom':
            orders = Order.objects.filter(user=user).order_by('-create_time')
        elif role == 'landlord':
            houses = House.objects.filter(user=user)
            house_ids = [house.id for house in houses]
            orders = Order.objects.filter(house_id__in=house_ids).order_by('-create_time')

        order_list = []
        for order in orders:
            # order.status = Order.ORDER_STATUS_CHOICES[order.status - 1][1]
            order_list.append({
                'amount': order.amount,
                'ctime': order.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'days': order.days,
                'end_date': order.end_date.strftime('%Y-%m-%d'),
                'img_url': order.house.index_image_url,
                'order_id': order.id,
                'start_date': order.begin_date.strftime('%Y-%m-%d'),
                'status': order.status,
                'title': order.house.title,
                'comment': order.comment,
            })
        return http.JsonResponse({
            'data': {
                'orders': order_list
            },
            "errmsg": "OK",
            "errno": RET.OK
        })

    def post(self, request):
        """保存订单信息和订单商品信息"""
        user = request.user
        # 1.获取参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 2.校验
        if not all([house_id, start_date, end_date]):
            return http.JsonResponse({'code': RET.PARAMERR,
                                      'errmsg': '缺少必传参数'})
        # 3.判断开始时间和结束时间是否合法
        # today_time = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        # today_time = timezone.now()
        # if start_date < today_time:
        #     return http.JsonResponse({'code': RET.PARAMERR,
        #                               'errmsg': '开始时间错误'})
        # elif end_date <= today_time:
        #     return http.JsonResponse({'code': RET.PARAMERR,
        #                               'errmsg': '结束时间错误'})
        # elif end_date < start_date:
        #     return http.JsonResponse({'code': RET.PARAMERR,
        #                               'errmsg': '时间错误'})
        # days = (end_date - start_date).days
        # if days < 1:
        #     return http.JsonResponse({'code': RET.PARAMERR,
        #                               'errmsg': '天数错误'})
        days = utils.days(start_date,end_date)
        if not days:
            return http.JsonResponse({'code': RET.PARAMERR,
                                          'errmsg': '时间错误'})

        # 房间是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception:
            return http.HttpResponseForbidden('房屋不存在')

        count = Order.objects.filter(house_id=house_id, begin_date__lt=end_date, end_date__gt=start_date).count()
        if count > 0:
            return http.JsonResponse({'code': RET.DATAERR,
                                      'errmsg': '订单冲突'})

        # 6.保存订单信息
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                order = Order.objects.create(
                    user=user,
                    house=house,
                    begin_date=start_date,
                    end_date=end_date,
                    days=days,
                    house_price=house.price,
                    amount=house.price * days,
                    status='WAIT_ACCEPT'
                )
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return http.JsonResponse({'code': RET.DATAERR,
                                          'errmsg': '增加出错'})
            transaction.savepoint_commit(save_id)
        # 7.返回
        return http.JsonResponse({
            'data': {
                'order_id': order.id,
            },
            'errno': RET.OK,
            'errmsg': 'ok'
        })

    def put(self, request):
        """房东接,拒单"""
        # 1.接受参数
        user = request.user
        json_dict = json.loads(request.body.decode())
        order_id = json_dict.get('order_id')
        reason = json_dict.get('reason')
        action = json_dict.get('action')
        # 校验
        if not all([action, order_id]):
            return http.JsonResponse({'code': RET.PARAMERR,
                                      'errmsg': '缺少必传参数'})
        try:
            Order.objects.filter(id=order_id,
                                 user=user)
        except Order.DoesNotExist:
            return http.HttpResponseForbidden('参数order_id错误')

        if action not in ('accept', 'reject'):
            return http.JsonResponse({'code': RET.PARAMERR,
                                      'errmsg': 'action参数错误'})
        # 查询订单
        try:
            order = Order.objects.get(id=order_id, status='WAIT_ACCEPT')
        except Exception:
            return http.JsonResponse({'code': RET.PARAMERR,
                                      'errmsg': '缺少拒绝原因'})

        # 2.判断action
        if action == 'accept':
            # 3.accept时修改订单状态,并保存

            order.status = 'WAIT_COMMENT'

            # 4.reject,填写comment修改状态,保存
        elif action == 'reject':
            order.status = 'REJECTED'
            if not reason:
                return http.JsonResponse({'code': RET.PARAMERR,
                                          'errmsg': '缺少拒绝原因'})
            order.comment = reason
        try:
            order.save()
        except Exception as e:
            return http.JsonResponse({'code': RET.DATAERR,
                                      'errmsg': '数据库保存错误'
                                      })
        # 5.返回
        return http.JsonResponse({
            "errno": RET.OK,
            "errmsg": "OK"
        })


# PUT /api/v1.0/orders/comment/
class OrderCommentView(View):
    def put(self, request):
        """评价订单商品"""
        # 接收参数
        user = request.user
        json_dict = json.loads(request.body.decode())
        order_id = json_dict.get('order_id')
        comment = json_dict.get('comment')
        # 校验参数
        if not all([order_id, comment]):
            return http.JsonResponse({'code': RET.DATAERR,
                                      'errmsg': '缺少参数'})
        try:
            order = Order.objects.get(id=order_id,
                                      user=user)
        except Order.DoesNotExist:
            return http.HttpResponseForbidden('参数order_id错误')

        # 保存订单商品评价数据
        order.comment = comment
        order.status = 'COMPLETE'
        try:
            order.save()
        except Exception as e:
            return http.JsonResponse({'code': RET.DATAERR,
                                      'errmsg': '数据库保存错误'
                                      })

        return http.JsonResponse({
            "errno": RET.OK,
            "errmsg": "OK"
        })
